//
//  MusicDetailViewController.m
//  FNer
//
//  Created by 王展 on 15/10/13.
//  Copyright (c) 2015年 wangzhan. All rights reserved.
//

#import "MusicDetailViewController.h"



//#import "UIImage+WebP.h"

#import "BaseCollectionView.h"
#import "MusicDetailCollectionViewCell.h"
#import "MusicDetail.h"

//#import "DataHandle.h"

#import <MediaPlayer/MediaPlayer.h>

#import <AVFoundation/AVFoundation.h>



@interface MusicDetailViewController ()

@property(nonatomic,retain)BaseCollectionView *musicCV;
@property(nonatomic,retain)MusicDetail *amusicDetail;
@property(nonatomic,retain)UILabel *info;
@property(nonatomic,retain)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,retain)UIImageView *imageView;
@property(nonatomic,retain)UILabel *name;
@property(nonatomic,retain)UIButton *startButton;

@property(nonatomic,retain)STKDataSource *dataSource;
@property(nonatomic,assign)BOOL start;

@property(nonatomic,retain)UIView *BlackView;
@property(nonatomic,retain)UILabel *timeLabel;
@property(nonatomic,retain)NSTimer *timer;

@property(nonatomic,retain)UIImage *startImage;
@property(nonatomic,retain)UIImage *endImage;

@property(nonatomic,assign)NSInteger shoucang;
@property(nonatomic,retain)Music *music;

@property(nonatomic,retain)UIImage *shoucangImage;
@property(nonatomic,retain)UIImage *quxiaoshoucangImage;
@property(nonatomic,retain)UILabel *titleLabel;

@property(nonatomic,retain)UIButton *nextButton;
@property(nonatomic,retain)UIButton *lastButton;

@property(nonatomic,retain)UIView *tempView1;
@property(nonatomic,retain)UIView *tempView2;
@property(nonatomic,retain)UIView *tempView3;


@property(nonatomic,retain)UISlider *musicSlider;

@property(nonatomic,copy)NSString *nowSource;

@property(nonatomic,retain)UIImage *musicPic;

@end

@implementation MusicDetailViewController


//创建单例音乐播放界面
+(instancetype)sharePlayerViewController
{
    static MusicDetailViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        player = [[MusicDetailViewController alloc] init];
        
    });
    return player;
}


//更新锁屏时的歌曲信息
-(void)newMusicInfo
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    [dict setObject:[MusicDetailViewController sharePlayerViewController].amusic.name forKey:MPMediaItemPropertyTitle];
    
    [dict setObject:@"FN" forKey:MPMediaItemPropertyArtist];
    
    [dict setObject:@"推荐" forKey:MPMediaItemPropertyAlbumTitle];
    
    if ([MusicDetailViewController sharePlayerViewController].amusicImage != nil) {
        MPMediaItemArtwork *albumArt = [ [MPMediaItemArtwork alloc] initWithImage:[MusicDetailViewController sharePlayerViewController].amusicImage];
        
        [dict setObject:albumArt forKey:MPMediaItemPropertyArtwork];
    }
    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    //申请后台,锁屏播放按钮功能
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
    
    //创建title
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    self.titleLabel.text = @"音乐";
    self.titleLabel.font = [UIFont systemFontOfSize:18 * XWIDTH];
    [self.titleLabel setTextAlignment:NSTextAlignmentCenter];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = self.titleLabel;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shipinbofangAction) name:@"shipin" object:nil];
    
    NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:@"nighting"];
    if ([string isEqualToString:@"yes"]) {
        self.titleLabel.textColor = [UIColor blackColor];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColoring:) name:@"changeColoring" object:nil];
    
    //初始化
    self.shoucang = NO;
    
    self.startImage = [UIImage imageNamed:@"iconfont-bofangqibofang.png"];
    self.endImage = [UIImage imageNamed:@"iconfont-zanting-2.png"];
    UIImage *lastImage = [UIImage imageNamed:@"iconfont-bofangqishangyiqu.png"];
    UIImage *nextImage = [UIImage imageNamed:@"iconfont-bofangqixiayiqu.png"];
    
    self.name = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, 10 * XWIDTH,  WIDTH - 20 * XWIDTH, 30 * XHIGHT)];
    
    self.info = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, 80 * XHIGHT, WIDTH - 20 * XWIDTH, 0)];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH)];
    self.imageView.userInteractionEnabled = YES;

    
    self.musicSlider = [[UISlider alloc] initWithFrame:CGRectMake(-5 * XWIDTH, WIDTH - 30 * XHIGHT, WIDTH + 10 * XWIDTH, 30 * XHIGHT)];
    
    UIImage *sliderImage = [UIImage imageNamed:@"music.png"];
    UIImage *newSliderImage = [self scaleToSize:sliderImage size:CGSizeMake(WIDTH + 10 * XWIDTH, 30 * XHIGHT)];
    [self.musicSlider setMaximumTrackImage:newSliderImage forState:0];
    
    UIImage *sliderImage2 = [UIImage imageNamed:@"musicTiao.png"];
    UIImage *newsliderImage2 = [self scaleToSize:sliderImage2 size:CGSizeMake(WIDTH + 10 * XWIDTH, 30 * XHIGHT)];
    [self.musicSlider setMinimumTrackImage:newsliderImage2 forState:0];
    
    
    UIImage *kuaiImage = [UIImage imageNamed:@"kuai.png"];
    UIImage *newKuaiImage = [self scaleToSize:kuaiImage size:CGSizeMake(10 * XWIDTH, 30 * XHIGHT)];
    [self.musicSlider setThumbImage:newKuaiImage forState:0];
    
    [self.imageView addSubview:self.musicSlider];
    [self.musicSlider addTarget:self action:@selector(musicSliderAction:) forControlEvents:UIControlEventValueChanged];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, WIDTH - 30 * XHIGHT, 150 * XWIDTH, 30 * XHIGHT)];
    self.timeLabel.font = [UIFont systemFontOfSize:15 * XHIGHT];
    self.timeLabel.textColor = [UIColor whiteColor];
    [self.imageView addSubview:self.timeLabel];
    [self.imageView bringSubviewToFront:self.timeLabel];
    
    self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.startButton setImage:self.endImage forState:0];
    self.startButton.titleLabel.textColor = [UIColor grayColor];
    [self.startButton addTarget:self action:@selector(startButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.startButton.frame = CGRectMake(200, WIDTH, 30 * XWIDTH, 30 * XWIDTH);
    self.startButton.center = CGPointMake(WIDTH / 2, WIDTH + 25 * XWIDTH);
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton.frame = CGRectMake(300 * XWIDTH, WIDTH + 12 * XWIDTH, 25 * XWIDTH , 25 * XWIDTH);
    [self.nextButton setImage:nextImage forState:0];
    [self.nextButton addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.lastButton.frame = CGRectMake(50 * XWIDTH, WIDTH + 12 * XWIDTH, 25 * XWIDTH, 25 * XWIDTH);
    [self.lastButton setImage:lastImage forState:0];
    [self.lastButton addTarget:self action:@selector(lastButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.tempView1 = [[UIView alloc] initWithFrame:CGRectMake(120 * XWIDTH, WIDTH, 1, 50 * XHIGHT)];
    self.tempView1.backgroundColor = [UIColor lightGrayColor];
    
    self.tempView2 = [[UIView alloc] initWithFrame:CGRectMake(250 * XWIDTH, WIDTH, 1, 50 * XHIGHT)];
    self.tempView2.backgroundColor = [UIColor lightGrayColor];
    
    self.tempView3 = [[UIView alloc] initWithFrame:CGRectMake(0, WIDTH + 50 * XHIGHT - 1, WIDTH, 1)];
    self.tempView3.backgroundColor = [UIColor lightGrayColor];
    
    //左侧按钮
    UIImage *leftImage = [UIImage imageNamed:@"导航栏_button_back_用于白和灰.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
    //初始化播放器
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.player.volume = 0.5;
    self.player.delegate = self;
    self.player.state = UIGestureRecognizerStateBegan;
    [self createMusicDetailView];
    
    [self.player play:self.amusic.source];
    
    self.nowSource = self.amusic.source;
}

//改变图片大小
-(UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

//控制音乐进度的滑动按钮
-(void)musicSliderAction:(UISlider *)sender
{
    if (self.player) {
        
        [self.player seekToTime:sender.value];
    }
}

//SKAudioPlayer方法
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"开始播放");
}
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"完成加载");
}
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    NSLog(@"播放状态改变");
}
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"结束播放");
    NSLog(   @"stopReason:  %d"    @"progress:  %f"  @"duration: %f",stopReason,progress,duration);
    if (stopReason == 1) {
        [self nextButtonAction];
    }
}

//传一个音乐对象
-(void)setAmusic:(Music *)amusic
{
    _amusic = amusic;
    
    if (self.nowSource != self.amusic.source) {
        [self.player play:self.amusic.source];
        self.nowSource = self.amusic.source;
        [self.startButton setImage:self.endImage forState:0];

        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.amusic.pic] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.amusicImage = image;
            [self newMusicInfo];
        }];
    }
    
    [self getMusicDetailData];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
    
    self.shoucangImage = [UIImage imageNamed:@"app_sc_an.png"];
    self.quxiaoshoucangImage = [UIImage imageNamed:@"app_sc.png"];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:nil style:UIBarButtonItemStylePlain target:self action:@selector(rigthButtonAction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:43 / 255.0 green:130 /255.0 blue:199 / 255.0 alpha:1];
   // NSMutableDictionary *myDic = [[DataHandle shareDataHandle] selectMusic];
 //   self.music = [myDic objectForKey:self.amusic.name];
    if (self.music) {
        self.shoucang = YES;
        self.navigationItem.rightBarButtonItem.image = self.shoucangImage;
    }else
    {
        self.shoucang = NO;
        self.navigationItem.rightBarButtonItem.image = self.quxiaoshoucangImage;
    }
}

//创建详情页面
-(void)createMusicDetailView
{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = CGSizeMake(WIDTH - 20, WIDTH + 30 * XHIGHT);
    self.flowLayout.minimumLineSpacing = 10 * XHIGHT;
    
    self.musicCV = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64) collectionViewLayout:self.flowLayout];
    self.musicCV.delegate = self;
    self.musicCV.dataSource = self;
    self.musicCV.bounces = NO;
    [self.view addSubview:self.musicCV];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 2;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.musicCV registerClass:[MusicDetailCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    MusicDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.row == 0) {
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.amusic.pic] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            self.amusicImage = image;
            [self newMusicInfo];
        }];
    
        [cell.contentView addSubview:self.imageView];
        [cell.contentView addSubview:self.nextButton];
        [cell.contentView addSubview:self.lastButton];
        [cell.contentView addSubview:self.startButton];
        [cell.contentView addSubview:self.tempView1];
        [cell.contentView addSubview:self.tempView2];
        [cell.contentView addSubview:self.tempView3];
    }
    else
    {
        self.name.text = self.amusicDetail.name;
        self.name.font = [UIFont systemFontOfSize:17 * XWIDTH];
        self.name.textColor = [UIColor colorWithRed:50 / 255.0 green:50 / 255.0 blue:50 / 255.0 alpha:1.0];
        self.name.numberOfLines = 0;
        self.name.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:self.name];
        
        self.info.numberOfLines = 0;
        self.info.font = [UIFont systemFontOfSize:16 * XWIDTH];
        self.info.textColor = [UIColor grayColor];
        [cell.contentView addSubview:self.info];
    }
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return CGSizeMake(WIDTH, WIDTH + 50 * XHIGHT);
    }
    else
    {
        self.info.text = self.amusicDetail.info;
        self.info.frame = CGRectMake(10 * XWIDTH, 50 * XHIGHT, WIDTH - 20 * XWIDTH, 0);
        [self.info sizeToFit];
        return CGSizeMake(WIDTH, self.info.frame.size.height + 90 * XHIGHT);
    }
}
//左侧按钮点击事件
-(void)leftButtonAction
{
    [self.navigationController popViewControllerAnimated:NO];
}

//获取详情数据
-(void)getMusicDetailData
{
    NSString *url_str = [NSString stringWithFormat:@"http://echosystem.kibey.com/sound/info?sound_id=%@",self.amusic.id];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"PHPSESSID=qtur65hr4cg4d60amesrt5ndm6" forHTTPHeaderField:@"Cookie"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];

    [manager GET:url_str parameters:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
        NSMutableDictionary *bigDic = responseObject;
        NSMutableDictionary *dic = [bigDic objectForKey:@"result"];
        self.amusicDetail = [[MusicDetail alloc] init];
        [self.amusicDetail setValuesForKeysWithDictionary:dic];
        [self.musicCV reloadData];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        NSLog(@"没有网络");
    }];
}

#warning 点击开始按钮触发
//点击开始按钮触发
-(void)startButtonAction
{
    if (self.player.state == STKAudioPlayerStatePaused) {
        
        NSLog(@"暂停");
        [self.startButton setImage:self.endImage forState:0];
        [self.player resume];
        
    }else if (self.player.state == STKAudioPlayerStatePlaying) {
        
        
        NSLog(@"播放");
        [self.startButton setImage:self.startImage forState:0];
        [self.player pause];
        
    }else
    {
        [self getMusicDetailData];
    }

}
//每隔一秒调用该方法
-(void)track
{
    self.musicSlider.maximumValue = self.player.duration;//音乐总时长
    self.musicSlider.value = self.player.progress;//当前进度
    
    //当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
}


-(void)rigthButtonAction
{
    if (self.shoucang == NO) {
      //  [[DataHandle shareDataHandle] insertMusicTable:self.amusic];
        self.navigationItem.rightBarButtonItem.image = self.shoucangImage;

        self.shoucang = YES;
    }
    else
    {
     //   [[DataHandle shareDataHandle] deleteMusic:self.amusic.name];
        self.navigationItem.rightBarButtonItem.image = self.quxiaoshoucangImage;

        self.shoucang = NO;
    }
    
}

-(void)changeColoring:(NSNotification *)notification
{
#warning 改的颜色
    self.titleLabel.textColor = [UIColor blackColor];
    
    NSString *string = [notification object];
    if ([string isEqualToString:@"no"]) {
        
#warning 原有颜色
        self.titleLabel.textColor = [UIColor whiteColor];
    }
    //保存当前状态值
    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"nighting"];
}

-(void)shipinbofangAction
{
    [self.player pause];
}

-(void)nextButtonAction
{

    [self.startButton setImage:self.endImage forState:0];
    self.indexRow++;
    if (self.indexRow == self.allMusicArray.count) {
        
        self.indexRow = 0;
    }
    self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
    
    [self.player play:self.amusic.source];
}


-(void)lastButtonAction
{
    [self.startButton setImage:self.endImage forState:0];
    self.indexRow--;
    if (self.indexRow == -1) {
        self.indexRow = self.allMusicArray.count - 1;
        
    }
    self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
    
    [self.player play:self.amusic.source];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
